/**
 * 
 */
package com.auth.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.auth.config.Config;
import com.auth.model.Account;
import com.auth.model.Role;
import com.service.AbstractService;
import com.util.ConfigUtil;
import com.utils.dbcp.ConnectionManager;
import com.utils.dbcp.ModelGenerator;
import com.utils.encrypt.MD5;

public class AccountServiceImpl extends AbstractService implements AccountService
{
	private Logger logger;
	
	private final String ENCRYPT_KEY = "@$^adpopo^$@";
	
	public AccountServiceImpl()
	{
		logger = Logger.getLogger(this.getClass());
		this.dbcp = ConfigUtil.get(Config.SECTION, Config.KEY_DBCP_NAME);
	}
	
	public void saveAccountLog(String id, String accountIp, String operate, String operateDesc)
	{
		/*
		String sql = "select * from account"
			com.service.sql.AccountServiceSql.saveAccountLog(id, accountIp, operate, operateDesc);
		logger.debug("sql: " + sql);
		ConnectionManager.getInstance().execute(ConfigManager.getConfig(ConfigManager.DBCP_NAME), sql);
		*/
	}
	
	public String encrypt(String str)
	{
		return MD5.computeMD5(str + ENCRYPT_KEY);
	}
	
	@Override
	public Account getAccount(String id, String password) 
	{		
		Account a = getAccount(id);
		if (a != null && (a.getPassword().equals(password) || a.getPassword().equals(encrypt(password))))
			return a;
		logger.info("[PASSWORD] [id:"+id+"] [password:"+password+"] [encrypt:"+encrypt(password)+"]");
		return null;
	}

	@Override
	public Account getAccount(String id) 
	{
		String sql = "select * from account where id='" + id + "'";
		ModelGenerator<Account> dbcpmg = new ModelGenerator<Account>(Account.class);
		return dbcpmg.generate(dbcp, sql);
	}

	@Override
	public List<Account> getAccounts()
	{
		String sql = "select * from account";
		logger.debug("sql: " + sql);
		ModelGenerator<Account> dbcpmg = new ModelGenerator<Account>(Account.class);
		return dbcpmg.generateList(dbcp, sql);
	}

	public boolean updatePassword(Account operator, String id, String password)
	{
		if (operator == null || operator.getId() == null || operator.getId().length() == 0)
			return false;
		String sql =
				"update account set password='" + encrypt(password) + "' " +
				"where id='" + id + "'";
		logger.debug("sql: " + sql);
		if (sql.length() > 0)
		{
			if (ConnectionManager.getInstance().execute(dbcp, sql))
			{
				Account lo = getAccount(id);
				this.logTableOperate("account", "update", operator, lo);
				return true;
			}
		}		
		return false;
	}
	
	@Override
	public boolean saveAccount(Account operator, String type, Account account)
	{
		if (operator == null || operator.getId() == null || operator.getId().length() == 0)
			return false;
		
		String sql = "";
		if (type.equalsIgnoreCase("insert"))
		{
				sql = 
				"insert into account(id,name,password,type,roleid,merchantids,channelids) " +
				"values('" + encodeDb(account.getId()) + "','" + encodeDb(account.getName()) + "','" + account.getPassword() + "'," +
						account.getType() + "," + account.getRoleId() + ",'" + account.getMerchantIds() + "','" +
						account.getChannelIds() + "')";
			
		}
		else if (type.equalsIgnoreCase("update"))
		{
			sql = 
				"update account set name='" + encodeDb(account.getName()) + "'," +
						// "password='" + encrypt(account.getPassword()) + "'," +
						"roleid=" + account.getRoleId() + "," +
						"type=" +account.getType() + "," +
						"merchantids='" + account.getMerchantIds() + "'," + 
						"channelids='" + account.getChannelIds() + "' " +
				" where id='" + account.getId() + "'";
		}
		else if (type.equalsIgnoreCase("delete"))
		{
			sql = "delete from account where id='" + encodeDb(account.getId()) + "'";
		}
		else
		{
			sql = "";
		}
		logger.debug("sql: " + sql);
		if (sql.length() > 0)
		{
			if (ConnectionManager.getInstance().execute(dbcp, sql))
			{
				Account lo = null;
				if (!type.equals("delete"))
					lo = getAccount(account.getId());
				this.logTableOperate("account", type, operator, lo);
			}
		}		
		return false;
	}

	@Override
	public List<Role> getRoles()
	{
		RoleService s = new RoleServiceImpl();
		return s.getRoles();
	}

	@Override
	public Role getRole(int id) 
	{
		RoleService s = new RoleServiceImpl();
		return s.getRole(id);
	}

	@Override
	public boolean saveAccountMerchant(Account operator,
			String accountId, List<Integer> merchantIds) {
		if (merchantIds == null)
			merchantIds = new ArrayList<Integer>();
		String sql[] = new String[merchantIds.size() + 1];
		sql[0] = "delete from accountmerchant where accountid='" + accountId + "'";
		for (int n = 0; n < merchantIds.size(); n++)
			sql[n + 1] = "insert into accountmerchant(accountid,merchantid) values('" + accountId + "'," + merchantIds.get(n) + ")";
		return ConnectionManager.getInstance().executeBatch(dbcp, sql);
	}

	@Override
	public boolean saveAccountSp(Account operator, 
			String accountId, List<Integer> spIds) {
		if (spIds == null)
			spIds = new ArrayList<Integer>();
		String sql[] = new String[spIds.size() + 1];
		sql[0] = "delete from accountsp where accountid='" + accountId + "'";
		for (int n = 0; n < spIds.size(); n++)
			sql[n + 1] = "insert into accountsp(accountid,spid) values('" + accountId + "'," + spIds.get(n) + ")";
		return ConnectionManager.getInstance().executeBatch(dbcp, sql);
	}

	@Override
	public boolean saveAccountChannel(Account operator, 
			String accountId, List<Integer> channelIds) {
		if (channelIds == null)
			channelIds = new ArrayList<Integer>();
		String sql[] = new String[channelIds.size() + 1];
		sql[0] = "delete from accountchannel where accountid='" + accountId + "'";
		for (int n = 0; n < channelIds.size(); n++)
			sql[n + 1] = "insert into accountchannel(accountid,channelid) values('" + accountId + "'," + channelIds.get(n) + ")";
		return ConnectionManager.getInstance().executeBatch(dbcp, sql);
	}

	@Override
	public List<Integer> getAccountMerchant(String accountId) {
		String sql = "select merchantid from accountmerchant where accountid='" + accountId + "'";
		ModelGenerator<Integer> mg = new ModelGenerator<Integer>(Integer.class);
		return mg.generateList(dbcp, sql);
	}

	@Override
	public List<Integer> getAccountSp(String accountId) {
		String sql = "select spid from accountsp where accountid='" + accountId + "'";
		ModelGenerator<Integer> mg = new ModelGenerator<Integer>(Integer.class);
		return mg.generateList(dbcp, sql);
	}

	@Override
	public List<Integer> getAccountChannel(String accountId) {
		String sql = "select channelid from accountchannel where accountid='" + accountId + "'";
		ModelGenerator<Integer> mg = new ModelGenerator<Integer>(Integer.class);
		return mg.generateList(dbcp, sql);
	}
	
	@Override
	public List<Integer> getAccountCp(String accountId) {
		String sql = "select cpid from accountcp where accountid='" + accountId + "'";
		ModelGenerator<Integer> mg = new ModelGenerator<Integer>(Integer.class);
		return mg.generateList(dbcp, sql);
	}
	
	@Override
	public boolean saveAccountCp(Account operator, 
			String accountId, List<Integer> cpIds) {
		if (cpIds == null)
			cpIds = new ArrayList<Integer>();
		String sql[] = new String[cpIds.size() + 1];
		sql[0] = "delete from accountcp where accountid='" + accountId + "'";
		for (int n = 0; n < cpIds.size(); n++)
			sql[n + 1] = "insert into accountcp(accountid,cpid) values('" + accountId + "'," + cpIds.get(n) + ")";
		return ConnectionManager.getInstance().executeBatch(dbcp, sql);
	}
}
